package com.warrantyhotel.android.ui;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.model.TransferObject;
import com.warrantyhotel.android.service.UpdateIntentService;
import com.warrantyhotel.android.util.DetachableResultReceiver;
import com.warrantyhotel.android.util.DetachableResultReceiver.Receiver;
import com.warrantyhotel.android.util.ToastUtil;

public class TransferEmailActivity extends Activity implements Receiver {

	// private ListView listView;
	// private ProgressDialog progress;
	// private LayoutInflater mInflater;
	// private AccountIdentifyObject[] result = null;
	// private static final int ADD_NEW_DIALOG = 1;
	// private String[] arrayAction;

	private DetachableResultReceiver receiver;
	private EditText edtTranferEmail;
	private static final int PICK_CONTACT = 56;
	private String warrantyId = null;
	private String uploadId = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.transfer);

		warrantyId = getIntent().getStringExtra(Keys._warrantyId);
		uploadId = getIntent().getStringExtra(Keys._account_upload_id);
		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);

		edtTranferEmail = (EditText) findViewById(R.id.email_tranfer);
		Button btnContactList = (Button) findViewById(R.id.transfer_button);
		btnContactList.setOnClickListener(new android.view.View.OnClickListener() {

			@Override
			public void onClick(View v) {
				final Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
				startActivityForResult(intent, PICK_CONTACT);

			}
		});

	}

	public void send(View view) {
		if (TextUtils.isEmpty(edtTranferEmail.getText().toString().trim())) {
			ToastUtil.showText(getApplicationContext(), getString(R.string.enter_email_address));
		} else if (!isEmailValid(edtTranferEmail.getText().toString().trim())) {
			ToastUtil.showText(getApplicationContext(), getString(R.string.incorrect_email));
		} else {
			if (warrantyId != null)
				doTransferWarantyEmail(edtTranferEmail.getText().toString().trim(), warrantyId);
			if (uploadId != null)
				doTransferUploadEmail(edtTranferEmail.getText().toString().trim(), uploadId);
		}
	}

	public void cancel(View view) {
		finish();
	}

	private void doTransferWarantyEmail(String email, String warrantyId) {
		Intent updateIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateIntentService.class);
		updateIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
		updateIntent.putExtra(Keys._warrantyId, warrantyId);
		updateIntent.putExtra(Keys._transferTargetEmail, email);
		updateIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.WARRANTY_SAVE);
		startService(updateIntent);
	}

	private void doTransferUploadEmail(String email, String uploadId) {
		Intent updateIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateIntentService.class);
		updateIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
		updateIntent.putExtra(Keys._account_upload_id, uploadId);
		updateIntent.putExtra(Keys._transferTargetEmail, email);
		updateIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.ACCOUNT_UPLOAD_TRANSFER);
		startService(updateIntent);
	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateIntentService.STATUS_RUNNING:
			break;
		case UpdateIntentService.STATUS_ERROR:
			break;
		case UpdateIntentService.STATUS_FINISHED:
			if (resultData.containsKey(Keys.actionIdentificator)) {
				TransferObject tObject = (TransferObject) resultData.getParcelable(Keys.isTransfer);
				ToastUtil.showText(getApplicationContext(), tObject.getMessage());
				if (tObject.isResult()) {
					finish();
				}
			}

			break;
		}
	}

	private boolean isEmailValid(String email) {
		boolean result = false;

		if (email != null) {
			Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
			Matcher matcher = pattern.matcher(email);
			result = matcher.matches();
		}
		return result;
	}

	@Override
	public void onActivityResult(int reqCode, int resultCode, Intent data) {
		super.onActivityResult(reqCode, resultCode, data);

		switch (reqCode) {
		case (PICK_CONTACT):
			if (resultCode == Activity.RESULT_OK) {
				Uri contactData = data.getData();
				Cursor c = managedQuery(contactData, null, null, null, null);
				if (c.moveToFirst()) {
					String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
					c = managedQuery(Email.CONTENT_URI, null, Email.CONTACT_ID + "=?", new String[] { id }, null);
					if (c.moveToFirst()) {
						String email = c.getString(c.getColumnIndex(Email.DATA1));
						edtTranferEmail.setText(email);
					}
				}
				break;
			}
		}
	}

}
